﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using Musicman.Business;
using System.Net.Mail;
using Musicman.Utilities;
using System.IO;

namespace MusicmanWeb
{
    public partial class ForgotPassword : MusicmanPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                string rndPassword = Membership.GeneratePassword(15, 5);
                Musicman.Common.Entities.User user = UserManager.Instance.ResetUserPassword(this.txtEmail.Text, rndPassword);
                if (user != null)
                {
                    string mailTemplate = "";
                    using (StreamReader sr = new StreamReader(File.Open(Server.MapPath("templates//reset_password.html"), FileMode.Open, FileAccess.Read)))
                    {
                        mailTemplate = sr.ReadToEnd();
                    }
                    MailMessage email = new MailMessage();
                    email.From = new MailAddress("musicmanservices@musicman.com", "Musicman");
                    email.To.Add(new MailAddress(txtEmail.Text));
                    email.Subject = "musicman password reset";
                    email.Body = String.Format(mailTemplate, user.Firstname + " " + user.Lastname, rndPassword, GetAppServer(), user.ActivationCode);
                    email.IsBodyHtml = true;
                    MailSender.Instance.SendMail(email);
                    this.lblResult.Text = "sucess";
                }
                else
                {
                    this.lblResult.Text = "fail";
                }
            }
        }

        protected void Check_Email(object source, ServerValidateEventArgs args)
        {
            args.IsValid = UserManager.Instance.CheckMail(args.Value);
        }
    }
}
